<template>
  <el-divider style="width: 100%"
    ><span style="font-size: 23px; font-family: '楷体'">免试申请审核</span></el-divider
  >
  <el-form style="margin-left: 85%">
    <el-form-item>
      <el-button type="primary" @click="exportExemInfo"
        ><el-icon style="margin-right: 5px" size="18px"><Upload /></el-icon>导出免试信息
      </el-button>
    </el-form-item>
  </el-form>
  <!--  搜索表单-->
  <el-form :inline="true" v-model="searchExem" style="margin-top: -20px">
    <el-form-item label="学号: ">
      <el-input
        style="width: 130px"
        v-model="searchExem.studentId"
        type="text"
        autocomplete="off"
        clearable
        placeholder="输入学号"
      />
    </el-form-item>
    <el-form-item label="姓名: ">
      <el-input
        style="width: 100px"
        v-model="searchExem.stuName"
        type="text"
        autocomplete="off"
        clearable
        placeholder="输入姓名"
      />
    </el-form-item>
    <el-form-item label="卓越班班级">
      <el-select
        v-model="searchExem.className"
        placeholder="选择卓越班名称"
        style="width: 200px"
        clearable
      >
        <el-option v-for="item in classNameList" :label="item.value" :value="item.value" />
      </el-select>
    </el-form-item>
    <el-form-item label="分数筛选">
      <el-input-number
        v-model="searchExem.exemScore"
        :min="0"
        :max="100"
        controls-position="right"
        placeholder="筛选该分数及以上"
        clearable
        style="width: 100px"
      />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm">搜索</el-button>
      <el-button type="info" @click="resetForm">清空 </el-button>
    </el-form-item>
  </el-form>

  <el-row v-if="searchExem.exemState === '已通过'">
    <el-button type="success" @click="passByExemIds">批量合格</el-button>
    <el-button type="danger" @click="noPassByExemIds">批量不合格</el-button> </el-row
  ><br />

  <el-tabs @tab-change="handleClick" v-model="searchExem.exemState">
    <el-tab-pane name="审核中">
      <template #label>
        <el-badge :value="noTotal" :max="99" :hidden="noTotal === 0">审核中</el-badge>
      </template>
    </el-tab-pane>
    <el-tab-pane label="被打回" name="未通过"></el-tab-pane>
    <el-tab-pane label="已通过" name="已通过"></el-tab-pane>
    <el-tab-pane label="合格" name="合格"></el-tab-pane>
    <el-tab-pane label="不合格" name="不合格"></el-tab-pane>
  </el-tabs>

  <!--  免试列表-->
  <el-table
    :data="exemInfo"
    border
    show-overflow-tooltip
    @selection-change="handleSelectionChange"
    @sort-change="sortByStuGrade"
  >
    <el-table-column v-if="searchExem.exemState === '已通过'" type="selection" width="40" />
    <el-table-column type="index" label="序号" width="60" align="center" />
    <el-table-column property="stuName" label="姓名" width="90px" align="center" />
    <el-table-column property="studentId" label="学号" width="140px" align="center" />
    <el-table-column property="stuSpeciality" label="专业" width="170px" align="center" sortable />
    <el-table-column
      property="stuGrade"
      label="年级"
      width="80px"
      align="center"
      sortable="custom"
    />
    <el-table-column prop="className" label="卓越班班级" align="center" />
    <el-table-column property="exemReason" label="申请理由" align="center" />
    <el-table-column
      property="exemDate"
      label="申请面试日期"
      width="140px"
      sortable
      align="center"
    />
    <el-table-column property="exemTime" label="面试时间" width="110px" sortable align="center" />
    <el-table-column prop="exemScore" label="面试分数" width="110" align="center" sortable>
      <template v-slot="row">
        <span v-if="row.row.exemScore != '' && row.row.exemScore != null">{{
          row.row.exemScore
        }}</span>
        <span v-else>无</span>
      </template>
    </el-table-column>
    <el-table-column property="exemState" label="状态" width="80px" align="center" />
    <el-table-column label="操作" align="center" width="250px">
      <template v-slot="{ row }">
        <el-button type="primary" @click="goDetail(row)">详情</el-button>
        <el-button v-if="{ ...row }.exemState == '已通过'" type="warning" @click="setScore(row)"
          >打分</el-button
        >
        <el-button
          v-if="{ ...row }.exemState == '审核中'"
          type="success"
          @click="pass({ ...row }.exemId, '已通过')"
          >通过</el-button
        >
        <el-button
          v-if="{ ...row }.exemState == '审核中'"
          type="danger"
          @click="Return({ ...row }.exemId, '未通过')"
          >打回</el-button
        >
        <el-button
          v-if="{ ...row }.exemState == '已通过' || { ...row }.exemState == '未通过'"
          type="danger"
          @click="cancel({ ...row }.exemId, '审核中')"
          >撤回</el-button
        >
        <el-button
          v-if="{ ...row }.exemState == '合格' || { ...row }.exemState == '不合格'"
          type="danger"
          @click="cancel({ ...row }.exemId, '已通过')"
          >撤回</el-button
        >
      </template>
    </el-table-column>
  </el-table>

  <!--  详情对话框-->
  <el-dialog
    v-model="dialogDetailVisible"
    align-center
    center
    title="学生详细信息"
    width="50%"
    style="height: 700px; background-color: #d1edc4"
  >
    <div class="info-box">
      <div class="item-box">
        <el-image
          v-if="diaForm.stuImage"
          style="width: 100px;display: block; float: left"
          :src="diaForm.stuImage"
        />
        <div
          v-else
          style="
          width: 100px;height: 150px;display: flex; float: left;
          background-color: #fff;align-items: center;justify-content: center;">
          无照片
        </div>
        <span class="label">姓名：</span>
        <span class="des">{{ diaForm.stuName }}</span>

        <span class="label">性别：</span>
        <span class="des">{{ diaForm.stuSex }}</span>

        <span class="label">学号：</span>
        <span class="des">{{ diaForm.studentId }}</span>

        <span class="label">电话：</span>
        <span class="des">{{ diaForm.stuPhone }}</span>

        <br />
        <span class="label">学院：</span>
        <span class="des">{{ diaForm.stuDepartment }}</span>

        <span class="label">专业：</span>
        <span class="des">{{ diaForm.stuSpeciality }}</span>

        <span class="label">年级：</span>
        <span class="des">{{ diaForm.stuGrade }}</span>

        <br />
        <span class="label">班级：</span>
        <span class="des">{{ diaForm.stuClass }}</span>

        <span class="label">邮箱：</span>
        <span class="des">{{ diaForm.email }}</span>

        <br />
        <span class="label">竞赛信息：</span>
        <div
          v-if="diaForm.contest != null && diaForm.contest != ''"
          style="color: #333333; margin-left: 80px"
          v-for="(item, index) in diaForm.contest"
          :key="index"
        >
          <div>
            奖项{{ index + 1 }}：{{
              item.conName + '&nbsp;&nbsp;&nbsp;&nbsp;获奖时间：' + item.conTime
            }}<br />
          </div>
        </div>
        <span v-else>无<br /></span>

        <span class="label">个人技能：</span>
        <span class="des">{{ diaForm.stuSkill + '，' + diaForm.stuSkillStack }}</span>

        <br />
        <span class="label">个人意向：</span>
        <span class="des">{{ diaForm.stuIntention }}</span>

        <br />
        <span class="label">申请免试理由：</span>
        <span class="des">{{ diaForm.exemReason }}</span>
      </div>
    </div>
  </el-dialog>
  <div style="margin-top: 10px">
    <el-pagination
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[10, 15, 20, 25]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      background
      @size-change="SizeChange"
      @current-change="CurrentChange"
    />
  </div>
  <!--  打分对话框-->
  <el-dialog v-model="dialogScoreVisible" align-center center title="面试成绩打分" width="30%">
    <el-form ref="scoreFormRef" :model="exemScoreInfo" label-width="100px">
      <el-form-item
        label-width="130px"
        label="免试中面试分数"
        prop="exemScore"
        :rules="[
          { required: true, message: '请填写分数' },
          { type: 'number', message: '分数必须是一个数字' }
        ]"
      >
        <el-input v-model.number="exemScoreInfo.exemScore" type="text" autocomplete="off" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span>
        <el-button @click="dialogScoreVisible = false">取消</el-button>
        <el-button type="primary" @click="submitScore(scoreFormRef)">保存</el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
import { h, onMounted, ref } from 'vue'
import { ElMessage, ElMessageBox, ElTable, FormInstance } from 'element-plus'
import { ExportExemInfo, getExemInfo, updateExemState } from '@/apis/exem'
import { getAllClassNameService } from '@/apis/dataCount'
import { setExemScore, noPassByIds, passByIds } from '@/apis/exem'

const pageSize = ref(10)
const currentPage = ref(1)
const total = ref(30)
const dialogDetailVisible = ref(false)
const diaForm = ref({})
const noTotal = ref(0)
const classNameList = ref([])
const dialogScoreVisible = ref(false)
const scoreFormRef = ref<FormInstance>()
const multipleSelection = ref([])
const selectIds = ref([])
const sortByStuGrade = (k: any) => {
  for (let i = 0; i < exemInfo.value.length; i++) {
    if (exemInfo.value[i].stuGrade === '大一') exemInfo.value[i].gradeKey = 1
    if (exemInfo.value[i].stuGrade === '大二') exemInfo.value[i].gradeKey = 2
    if (exemInfo.value[i].stuGrade === '大三') exemInfo.value[i].gradeKey = 3
    if (exemInfo.value[i].stuGrade === '大四') exemInfo.value[i].gradeKey = 4
  }
  if (k.order === 'ascending') {
    exemInfo.value.sort((a, b) => (a.gradeKey > b.gradeKey ? 1 : -1))
  }
  if (k.order === 'descending') {
    exemInfo.value.sort((a, b) => (a.gradeKey > b.gradeKey ? -1 : 1))
  }
}
const exemScoreInfo = ref({
  studentId: '',
  exemId: '',
  exemScore: ''
})
const exemStateInfo = ref({
  exemId: NaN,
  exemState: ''
})

const handleClick = () => {
  page()
}
const submitForm = () => {
  currentPage.value = 1
  page()
}
const resetForm = () => {
  searchExem.value.studentId = ''
  searchExem.value.stuName = ''
  searchExem.value.className = ''
  searchExem.value.exemScore = ''
  page()
}
const passByExemIds = () => {
  if (multipleSelection.value === null || multipleSelection.value.length === 0) {
    ElMessage({ type: 'error', message: '未选择合格人员' })
    return false
  }
  ElMessageBox.confirm('确认该批学生面试合格吗？', '提醒', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
    center: true
  })
    .then(() => {
      for (let i = 0; i < multipleSelection.value.length; i++) {
        selectIds.value[i] = multipleSelection.value[i].exemId
      }
      passByIds(selectIds.value).then((res) => {
        if (res.data.code === 1) {
          ElMessage({ type: 'success', message: '操作成功' })
          page()
        } else {
          ElMessage({ type: 'error', message: res.data.msg })
        }
      })
    })
    .catch(() => {})
}
const noPassByExemIds = () => {
  if (multipleSelection.value === null || multipleSelection.value.length === 0) {
    ElMessage({ type: 'error', message: '未选择不合格人员' })
    return false
  }
  ElMessageBox.confirm('确认该批学生面试不合格吗？', '提醒', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
    center: true
  })
    .then(() => {
      for (let i = 0; i < multipleSelection.value.length; i++) {
        selectIds.value[i] = multipleSelection.value[i].exemId
      }
      noPassByIds(selectIds.value).then((res) => {
        if (res.data.code === 1) {
          ElMessage({ type: 'success', message: '操作成功' })
          page()
        } else {
          ElMessage({ type: 'error', message: res.data.msg })
        }
      })
    })
    .catch(() => {})
}
const handleSelectionChange = (val: number[]) => {
  multipleSelection.value = val
}
const searchExem = ref({
  studentId: '',
  stuName: '',
  className: '',
  exemState: '审核中',
  exemScore: ''
})

interface ExemInfo {
  exemId: number
  stuName: string
  studentId: string
  stuSpeciality: string
  stuGrade: string
  exemReason: string
  exemState: string
}

const exemInfo = ref<ExemInfo[]>([])

const page = () => {
  getExemInfo(
    currentPage.value,
    pageSize.value,
    searchExem.value.studentId,
    searchExem.value.stuName,
    searchExem.value.className,
    searchExem.value.exemState,
    searchExem.value.exemScore
  ).then((res) => {
    if (res.data.code === 1) {
      console.log('获取成功')
      exemInfo.value = res.data.data.rows
      console.log(exemInfo.value)
      if (searchExem.value.exemState === '审核中') {
        noTotal.value = res.data.data.total
      }
      total.value = res.data.data.total
    } else {
      ElMessage({ type: 'error', message: res.data.msg })
      console.log('获取失败')
    }
  })
}

// 打回
const Return = (exemId: number, exemState: string) => {
  ElMessageBox.confirm('确认打回该申请吗?', '警告', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
    center: true
  })
    .then(() => {
      exemStateInfo.value.exemId = exemId
      exemStateInfo.value.exemState = exemState
      updateExemState(exemStateInfo.value).then((res) => {
        if (res.data.code === 1) {
          ElMessage({ type: 'success', message: '打回成功' })
          page()
        } else {
          ElMessage({ type: 'error', message: res.data.msg })
        }
      })
    })
    .catch(() => {
      ElMessage({ type: 'info', message: '取消打回' })
    })
}
// 撤回
const cancel = (exemId: number, exemState: string) => {
  ElMessageBox({
    title: '提醒',
    message: h('p', null, [
      h('span', null, '撤回后该学生免试状态将改为 '),
      h('strong', { style: 'color: #E6A23C' }, exemState),
      h('span', null, ' 确定撤回吗?')
    ]),
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    showCancelButton: true,
    center: true,
    type: 'warning'
  })
    .then(() => {
      exemStateInfo.value.exemId = exemId
      exemStateInfo.value.exemState = exemState
      updateExemState(exemStateInfo.value).then((res) => {
        if (res.data.code === 1) {
          ElMessage({ type: 'success', message: '撤回成功' })
          page()
        } else {
          ElMessage({ type: 'error', message: res.data.msg })
        }
      })
    })
    .catch(() => {
      ElMessage({ type: 'info', message: '取消撤回' })
    })
}
const exportExemInfo = async () => {
  if (searchExem.value.className === '') {
    ElMessage({ type: 'error', message: '请选择导出哪一届卓越班学生免试信息' })
    return
  }
  const { data } = await ExportExemInfo(searchExem.value.exemState, searchExem.value.className)
  let url = window.URL.createObjectURL(data)
  var a = document.createElement('a')
  document.body.appendChild(a)
  a.href = url
  a.download = '免试人员信息表.xlsx'
  a.click()
  window.URL.revokeObjectURL(url)
}

// 通过
const pass = (exemId: number, exemState: string) => {
  ElMessageBox.confirm('确认通过该申请吗?', '警告', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
    center: true
  })
    .then(() => {
      exemStateInfo.value.exemId = exemId
      exemStateInfo.value.exemState = exemState
      updateExemState(exemStateInfo.value).then((res) => {
        if (res.data.code === 1) {
          ElMessage({ type: 'success', message: '已通过该申请' })
          page()
        } else {
          ElMessage({ type: 'error', message: res.data.msg })
        }
      })
    })
    .catch(() => {})
}

onMounted(() => {
  getAllClassNameService().then((res) => {
    if (res.data.code === 1) {
      let className = res.data.data
      for (let v of className) {
        classNameList.value.push({ value: v })
      }
    } else {
      ElMessage({ type: 'error', message: res.data.msg })
    }
  })
  page()
})
const SizeChange = (val: number) => {
  pageSize.value = val
  page()
}
const CurrentChange = (val: number) => {
  currentPage.value = val
  page()
}

const goDetail = (row: any) => {
  diaForm.value = {}
  dialogDetailVisible.value = true
  diaForm.value = { ...row }
}

const setScore = (row: any) => {
  dialogScoreVisible.value = true
  exemScoreInfo.value.exemScore = { ...row }.exemScore
  exemScoreInfo.value.exemId = { ...row }.exemId
  exemScoreInfo.value.studentId = { ...row }.studentId
}

const submitScore = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      setExemScore(exemScoreInfo.value).then((res) => {
        if (res.data.code === 1) {
          exemScoreInfo.value = {}
          dialogScoreVisible.value = false
          ElMessage({ type: 'success', message: '打分成功' })
          page()
        } else {
          ElMessage({ type: 'error', message: res.data.msg })
        }
      })
    } else {
      return false
    }
  })
}
</script>
<style>
.info-box {
  margin: -15px -10px 20px;
}
.info-box .item-box {
  height: 20px;
  line-height: 50px;
  font-size: 14px;
  font-weight: 400;
  color: #666666;
  text-align: left;
  margin-bottom: 14px;
}
.info-box .item-box .label {
  width: 50px;
  margin-left: 40px;
}
.info-box .item-box .des {
  color: #333333;
}
</style>
